using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using FreeLancer.HRB.Services;
using FreeLancer.HRB.Domains;
using FreeLancer.HRB.Core;
using FreeLancer.HRB.Core.Services;
using System.Threading;
using DevExpress.Web.ASPxUploadControl;
using System.IO;

namespace FreeLancer.HRB.WebApp.Admin.Pages
{
  public partial class EditPost : System.Web.UI.Page
  {
    #region Members

    private FreeLancer.HRB.Domains.Posts _post;
    private Guid _categoryId = Guid.Empty;
    private int _languageId = 0;
    DateTime now = DateTime.Now;

    #endregion

    #region Page Events

    protected void Page_Init(object sender, EventArgs e)
    {
      //string path = "./"; //Utils.AbsoluteWebRoot.AbsoluteUri.Replace("~/", "");
      //ASPxHtmlEditor.SettingsImageUpload.UploadImageFolder = path + "Images/PostImages/";
      LoadLanguage();

      if (cboLanguage.Items.Count > 0)
        _languageId = int.Parse(cboLanguage.Items[0].Value);
      else
        _languageId = 0;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
      if (!string.IsNullOrEmpty(cboLanguage.SelectedValue))
      {
        _languageId = int.Parse(cboLanguage.SelectedValue);
      }

      if (!IsPostBack)
      {
        InitializePostContent();
        LoadCategory();
        EnabledAttachedFile();
      }

      EnabledEditingLanguage();

      lblErrorUpdateFailed.Visible = false;
      lblErrorLoadFailed.Visible = false;
    }

    private void EnabledAttachedFile()
    {
      if ((_post == null) || (string.IsNullOrEmpty(_post.AttachedPath)))
      {
        ASPxUploadControlFile.Visible = true;
        linkUploadedFile.Visible = false;
        chkUploadedFile.Visible = false;
        chkUploadedFile.Checked = false;
      }
      else
      {
        ASPxUploadControlFile.Visible = false;
        linkUploadedFile.Visible = true;
        chkUploadedFile.Visible = true;
        chkUploadedFile.Checked = true;
        linkUploadedFile.Text = _post.AttachedPath.Substring(_post.AttachedPath.IndexOf('_') + 1);
        linkUploadedFile.NavigateUrl = 
          Utils.RelativeWebRoot + "Files/PostFiles/" + _post.AttachedPath;
      }
    }

    #endregion

    #region Controls Events

    #region cboLanguage Events

    protected void cboLanguage_SelectedIndexChanged(object sender, EventArgs e)
    {
      InitializePostContent();
    }

    #endregion

    #region cboCategory  Events

    protected void cboCategory_DataBound(object sender, EventArgs e)
    {
      cboCategory.Items.Insert(0, new ListItem(Resources.labels.noneItem, "0"));
    }

    #endregion

    protected void btnSave_Click(object sender, EventArgs e)
    {
      PostsService postService = GlobalCache.PostServiceInstance;
      

      GetPostContent();
      bool flagNew = _post.IsNew;

      try
      {
        using (ConnectionScope.CreateTransaction())
        {
          postService.Save(_post);
          SavePostCategory();
          
          if (ConnectionScope.Complete())
          {
            lblTime.Text = _post.DateModified.ToString();
          }
          else
          {
            LoggingService.LogError("Admin-EditPost Page", "Can not complete transaction when saving Post.",
              null, LoggingService.DefaultCategory, true);

            lblErrorUpdateFailed.Visible = true;
          }
        }
      }
      catch (Exception ex)
      {
        LoggingService.LogCritical("Admin-EditPost Page", "Can not save Post.", ex,
              LoggingService.DefaultCategory, true);

        lblErrorUpdateFailed.Visible = true;
      }

      if (flagNew)
        Response.Redirect("EditPost.aspx?Id=" + _post.PostId);

      PostCategoryService postCategoryService = new PostCategoryService();
      TList<PostCategory> postCategoryItems = postCategoryService.GetByPostId(_post.PostId);
      if (postCategoryItems.Count > 0)
      {
        cboCategory.SelectedValue = postCategoryItems[0].CategoryId.ToString();
        cboLanguage.SelectedValue = postCategoryItems[0].LanguageId.ToString();
      }

      //Special case
      if (_post != null)
        ASPxImage.ImageUrl = _post.ImagePath;
    }

    #endregion

    #region Page Processing

    /// <summary>
    /// Initialize language to combobox
    /// </summary>
    private void LoadLanguage()
    {
      int total = 0;
      LanguagesService languageService = new LanguagesService();
      TList<Languages> languages = languageService.GetPaged("IsActive='True'", string.Empty, 0, 3, out total);
      cboLanguage.DataSource = languages;
      cboLanguage.DataTextField = "Name";
      cboLanguage.DataValueField = "LanguageID";
      cboLanguage.DataBind();
    }

    private void LoadCategory()
    {
      int total = 0;
      CategoriesService categoryService = GlobalCache.CategoriesService;
      TList<Categories> categories = //categoryService.GetByLanguageId(_languageId);
        categoryService.GetPaged("LanguageID=" + _languageId +
          "AND CategoryID NOT IN ('2e9e24b0-c419-48ec-91c0-1bdbb43a8500', '792ad48a-3bec-4565-8600-5f9162e4b474')",
          string.Empty, 0, 100, out total);
      categories.Sort("CategoryName");

      cboCategory.DataSource = categories;
      cboCategory.DataTextField = "CategoryName";
      cboCategory.DataValueField = "CategoryID";
      cboCategory.DataBind();
    }

    /// <summary>
    /// Load Post
    /// </summary>
    private void LoadPost()
    {
      //if (!string.IsNullOrEmpty(cboLanguage.SelectedValue))
      //{
      //  _languageId = int.Parse(cboLanguage.SelectedValue);
      //}
      //LoadCategory();

      string postId = Request["Id"];
      if (!string.IsNullOrEmpty(postId))
      {
        if (postId.Length == 36)
        {
          try
          {
            PostsService service = GlobalCache.PostServiceInstance;
            _post = service.GetByPostId(new Guid(postId));
          }
          catch (Exception e)
          {
            LoggingService.LogCritical("Admin-EditPost Page", "Can not load data for Post",
              null, LoggingService.DefaultCategory, true);

            lblErrorLoadFailed.Visible = true;
          }
        }
      }
    }

    /// <summary>
    /// Load Post content
    /// </summary>
    private void InitializePostContent()
    {
      LoadPost();

      if (_post != null)
      {
        txtTitle.Text = _post.Title;
        txtDescription.Text = _post.Description;
        txtSlug.Text = _post.Slug;
        ASPxHtmlEditor.Html = _post.PostContent;

        chkIsCommentAllowed.Checked = (bool)_post.IsCommentAllowed;
        chkIsPublished.Checked = _post.IsPublished;

        lblTime.Text = _post.DateModified.ToString();
        
        lblUpdateAt.Visible = true;
        lblTime.Visible = true;

        if (!string.IsNullOrEmpty(_post.ImagePath))
          ASPxImage.ImageUrl = PostImagePath + _post.ImagePath;

        PostCategoryService postCategoryService = new PostCategoryService();
        TList<PostCategory> postCategoryItems = postCategoryService.GetByPostId(_post.PostId);
        if (postCategoryItems.Count > 0)
        {
          cboCategory.SelectedValue = postCategoryItems[0].CategoryId.ToString();
          cboLanguage.SelectedValue = postCategoryItems[0].LanguageId.ToString();
        }
      }
      else
      {
        //New post
        lblUpdateAt.Visible = false;
        lblTime.Visible = false;
      }
    }

    /// <summary>
    /// Put data to Post
    /// </summary>
    private void GetPostContent()
    {
      LoadPost();

      DateTime now = DateTime.Now;
      //New Page
      if (_post == null)
      {
        _post = new FreeLancer.HRB.Domains.Posts();
        _post.PostId = Guid.NewGuid();
        _post.DateCreated = now;
      }

      _post.Title = txtTitle.Text;
      _post.Description = txtDescription.Text;
      _post.Slug = txtSlug.Text;
      _post.PostContent = ASPxHtmlEditor.Html;
      _post.IsPublished = chkIsPublished.Checked;
      _post.DateModified = now;
      _post.Author = Thread.CurrentPrincipal.Identity.Name;
      _post.IsCommentAllowed = chkIsCommentAllowed.Checked;

      if (!string.IsNullOrEmpty(ASPxTextBoxImageName.Text))
        _post.ImagePath = ASPxTextBoxImageName.Text;
      else
        _post.ImagePath = null;

      if ((chkUploadedFile.Visible == false) && (string.IsNullOrEmpty(linkUploadedFile.Text)))
      {
        if (!string.IsNullOrEmpty(ASPxUploadControlFile.FileName))
          _post.AttachedPath = now.ToString("yyyyMMddhhmmss") + "_" + ASPxUploadControlFile.FileName;
        else
          _post.AttachedPath = null;
      }
      else
      {
        if (chkUploadedFile.Checked == false)
        {
          if (_post.AttachedPath != null)
          {
            try
            {
              File.Delete(Server.MapPath("~/Files/PostFiles/") + _post.AttachedPath);
            }
            catch (Exception ex)
            {
              LoggingService.LogCritical("Admin-EditPost Page", "Can not delete attached file.", ex,
                LoggingService.DefaultCategory, true);
            }
            _post.AttachedPath = null;
          }
        }
      }

      EnabledAttachedFile();
    }

    private void SavePostCategory()
    {
      PostCategoryService postCategoryService = new PostCategoryService();
      TList<PostCategory> postCategoryItems = postCategoryService.GetByPostId(_post.PostId);
      PostCategory postCategoryItem = null;

      if (cboCategory.SelectedIndex < 0)
        throw new Exception("There is no category");

      _categoryId = new Guid(cboCategory.SelectedValue);

      if (postCategoryItems.Count == 0)
        postCategoryItem = new PostCategory();
      else
      {
        //foreach (PostCategory postCateItem in postCategoryItems)
        //{
        //  if ((postCateItem.LanguageId == _languageId) && (postCateItem.CategoryId == _categoryId))
        //  {
        //    postCategoryItem = postCateItem;
        //    break;
        //  }
        //}
        if (postCategoryItems.Count > 0)
          postCategoryItem = postCategoryItems[0];

        if (postCategoryItem == null)
          postCategoryItem = new PostCategory();
      }

      postCategoryItem.PostId = _post.PostId;
      postCategoryItem.CategoryId = _categoryId;
      postCategoryItem.LanguageId = _languageId;

      postCategoryService.Save(postCategoryItem);
    }

    private void EnabledEditingLanguage()
    {
      string postId = Request["Id"];
      if (!string.IsNullOrEmpty(postId))
      {
        if (postId.Length == 36)
        {
          cboLanguage.Enabled = false;
          //lblLanguage.Visible = false;
        }
        else
        {
          cboLanguage.Enabled = true;
          //lblLanguage.Visible = true;
        }
      }
    }


    #endregion

    #region Upload

    protected void ASPxUploadControl_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
    {
      if (e.IsValid)
      {
        string path = Server.MapPath("~/Images/PostImages/");

        path = path + now.ToString("yyyy_MM_dd_hh_mm_ss") + "_" + ASPxUploadControl.FileName;
        
        ASPxUploadControl.SaveAs(path, true);

        e.CallbackData = now.ToString("yyyy_MM_dd_hh_mm_ss") + "_" + ASPxUploadControl.FileName;
      }
    }

    protected void ASPxUploadControlFile_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
    {
      if (e.IsValid)
      {
        string path = Server.MapPath("~/Files/PostFiles/");
        
        path = path + now.ToString("yyyyMMddhhmmss") + "_" + ASPxUploadControlFile.FileName;

        ASPxUploadControlFile.SaveAs(path, true);
      }
    }

    #endregion

    /// <summary>
    /// ../../PostImages/
    /// </summary>
    public const string PostImagePath = "../../Images/PostImages/";
  }
}
